"""
vas zookeeper 测试工具
功能：
1. 创建视频节点（永久节点） /channel/channel_id，在其中保存视频数据
2. 删除视频节点，如果视频节点下面有分析节点，则分析节点一并删除
"""
import json
import traceback

from kazoo.client import KazooClient

HOST = '127.0.0.1:2181'
ROOT = '/channel'
CHANNELS = [{
    "channel": "channel_001",  # 视频源ID
    "url": "test_video.mp4",  # 视频源地址
    "tasks": [{  # 视频源分析任务列表
        "type": "HUMAN-DETECTION",  # 任务名
        "roi": [],  # 分析区域
        "interval": 2  # 报警间隔
    }]
}]


def add_channels(host, channels):
    client = KazooClient(hosts=host, read_only=False)
    client.start()
    # check the root node
    if not client.exists(ROOT):
        client.create(ROOT)
    for ch in channels:
        try:
            path = f'{ROOT}/{ch["channel"]}'
            data = json.dumps(ch).encode('utf8')
            assert not client.exists(path)
            client.create(path=path, value=data)
            print('zk node created', path)
        except Exception as e:
            print(e)
            traceback.print_exc()
    client.stop()
    client.close()


def get_all_channels(host):
    client = KazooClient(hosts=host, read_only=False)
    client.start()
    # check the root node
    if not client.exists(ROOT):
        client.create(ROOT)
    res = client.get_children(ROOT)
    client.stop()
    client.close()
    return res


def delete_zk_node(client, path):
    assert client.exists(path)
    children = client.get_children(path)
    for child in children:
        delete_zk_node(client, f'{path}/{child}')
    client.delete(path)
    print('zk node deleted', path)


def delete_channel(host, cid):
    client = KazooClient(hosts=host, read_only=False)
    client.start()
    # check the root node
    if not client.exists(ROOT):
        client.create(ROOT)
    try:
        path = f'{ROOT}/{cid}'
        delete_zk_node(client, path)

    except Exception as e:
        print(e)
        traceback.print_exc()
    client.stop()
    client.close()


if __name__ == '__main__':
    add_channels(HOST, CHANNELS)
    channels = get_all_channels(HOST)
    # for c in channels:
    #     delete_channel(HOST, c)
